package escom.linearProgramming;

import java.util.ArrayList;
import java.util.List;


import escom.linearProgramming.model.SimplexMetodoTabular;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.*;
import android.widget.*;

import static android.view.ViewGroup.LayoutParams.FILL_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static android.widget.LinearLayout.HORIZONTAL;;


public class captureData extends Activity{
	private static final String CLASSTAG = captureData.class.getSimpleName();
	private static final int MENU_RESOLVER = Menu.FIRST;
	private static final int MENU_GRAFICAR = Menu.FIRST+1;
	private static final int ERROR_GRAF_T1 = 1;
	private static final int ERROR_RESOL_T1 = 2;
	private static final String TXT_ERROR_GRAF_T1 = "No se puede Graficar con mas de dos variables";
	private static final String TXTERROR_RESOL_T1 = "Faltan Campos para llenar";
	
	private List<EditText> editTextList = new ArrayList<EditText>();
	private TextView labelV;
	private TextView labelDir;
	private TextView labelRHS;
	private TextView labelNombre;
	public int variables;
	public int restricciones;
	public int idRadio;
	int count;
	LpApp app;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        app = (LpApp) getApplication();
        
        labelNombre = new TextView(this);
        labelNombre.setText("Nombre Problema: " + app.getNombre());
        labelNombre.setWidth(WRAP_CONTENT);
        
		variables = app.getVariables();
		restricciones = app.getRestricciones();
		idRadio = app.getIdRadio();	
		
		labelV = new TextView(this);
		labelV.setText("Variable-->");
		labelDir = new TextView(this);
		labelDir.setText("Direction");
		labelRHS = new TextView(this);
		labelRHS.setText("R.H.S.");
		
        setContentView(R.layout.capturedata);
           
        LinearLayout linearLayout = new LinearLayout(this);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(FILL_PARENT, WRAP_CONTENT);
        linearLayout.setLayoutParams(params);
        linearLayout.setOrientation(HORIZONTAL);
 
        //Variable Count:Cuantos TextFields son
        count = ((variables+2)*(restricciones+1));
        linearLayout.addView(tableLayout(count));
        setContentView(linearLayout);
        
       
    }
    

    
    private TableLayout tableLayout(int count) {
        TableLayout tableLayout = new TableLayout(this);
        TableRow tableRowName = new TableRow(this);
        TableRow tableRow = new TableRow(this);
        tableLayout.setStretchAllColumns(true);
        int noOfRows = count / (variables+2);
        
        //set Headers
        tableLayout.addView(tableRowName);
        tableLayout.addView(tableRow);
        tableRowName.addView(labelNombre);
        tableRow.addView(labelV);
        for(int i = 0; i < variables; i++)
        	tableRow.addView(textView(i));
        tableRow.addView(labelDir);
        tableRow.addView(labelRHS);
        
        //set TextFields
        for (int i = 0; i < noOfRows; i++) {
            int rowId = (restricciones+2) * i;
            tableLayout.addView(createOneFullRow(rowId,i+1));
        }
        int individualCells = count % (variables+2);
        tableLayout.addView(createLeftOverCells(individualCells, count));
        return tableLayout;
    }
 
    private TableRow createLeftOverCells(int individualCells, int count) {
        TableRow tableRow = new TableRow(this);
        tableRow.setPadding(0, 10, 0, 0);
        int rowId = count - individualCells;
        for (int i = 1; i <= individualCells; i++) {
            tableRow.addView(editText(String.valueOf(rowId + i)));
        }
        return tableRow;
    }
 
    private TableRow createOneFullRow(int rowId, int j) {
        TableRow tableRow = new TableRow(this);
        tableRow.setPadding(0, 10, 0, 0);
        tableRow.addView(textRow(j));
        int modi=0;
        for (int i = 0; i < (variables+2); i++) {
        	modi=i%(variables+2);
        	if (variables==modi){
        		tableRow.addView(spinner(String.valueOf(rowId+i)));    		
        	}else{
        		tableRow.addView(editText(String.valueOf(rowId + i)));
        	}        
       }
        return tableRow;
    }
 
    private Spinner spinner(String hint){
    	String [] opciones = {"=","<=",">=","<",">"};
    	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.text1,opciones);
    	Spinner spinner = new Spinner(this);
    	spinner.setId(Integer.valueOf(hint));
    	spinner.setAdapter(adapter);
    	return spinner;
    	
    }
    
    
    
    private EditText editText(String hint) {
        EditText editText = new EditText(this);
        editText.setId(Integer.valueOf(hint));
        editText.setHint("n");
        editText.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);   
        editTextList.add(editText);
        return editText;
    }
    
    private TextView textView(int n){
    	
    	TextView textView = new TextView(this);
    	textView.setId(Integer.valueOf(n));
    	textView.setText("x" + (n+1));
    	return textView;	
    	
    }
    
   private TextView textRow(int n){
    	
    	TextView textView = new TextView(this);
    	textView.setId(Integer.valueOf(n));
    	//Log.i(CLASSTAG, "id Radio despues: "+app.MAX_ID);
    	
    	if(n == 1 && idRadio==app.MAX_ID)
    		textView.setText("Maximize");
    	else if(n == 1 && idRadio==app.MIN_ID)
    		textView.setText("Minimize");
    	else
    		textView.setText("C" + (n-1));
    	
    	
    	return textView;	
    	
    }
	
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
	   super.onCreateOptionsMenu(menu);
	   menu.add(0, captureData.MENU_RESOLVER, 0, R.string.Resolver).setIcon(
	            android.R.drawable.ic_menu_more);
	   menu.add(0, captureData.MENU_GRAFICAR, 1, R.string.Graficar).setIcon(
	            android.R.drawable.ic_menu_more);
       return true;
   }
   
   
   @Override
   public boolean onMenuItemSelected(int featureId, MenuItem item) {
	   switch (item.getItemId()) {
           case MENU_RESOLVER:
        	   
        	   if (validarCampos()==true){
        		   String ana = AnalisisResolver();
        		   MetodoRun(ana);   
        	   }else{
        		   showDialog(ERROR_RESOL_T1);
        	   }
        	   

               return true;
           case MENU_GRAFICAR:
        	   if(variables==2)
        	   		{
        		   if(validarCampos()==true)
        		   {
        		   	app.setEq(AnalisisGraficar());
        		   	Intent in = new Intent(captureData.this,AdvancedMultipleSeriesGraph.class);
       	           	startActivity(in);
        		   }
        		   else{
        			   showDialog(ERROR_RESOL_T1);
        		   }
        	   	}
        	   else
        		   showDialog(ERROR_GRAF_T1);
               return true;
           default:
               return  super.onMenuItemSelected(featureId, item);
       }
   }
   protected Dialog onCreateDialog(int id) {
       Dialog dialogo = null;
       switch(id)
       {
           case ERROR_GRAF_T1:
               dialogo = crearDialogoVar(ERROR_GRAF_T1);
               break;
               
           case ERROR_RESOL_T1:
        	   dialogo = crearDialogoVar(ERROR_RESOL_T1);
               break;
            
           default:
               dialogo = null;
               break;
       }
    
       return dialogo;
   }
   
   private Dialog crearDialogoVar(int tipo)
   {
       AlertDialog.Builder builder = new AlertDialog.Builder(this);
       
       builder.setTitle("Error!");
       
       switch(tipo){
       
       case 1:	builder.setMessage(TXT_ERROR_GRAF_T1);
       			break;
       case 2:	builder.setMessage(TXTERROR_RESOL_T1);
    	   		break;
    	   
       }
       
       
       
       
       builder.setPositiveButton("OK", new OnClickListener() {
           public void onClick(DialogInterface dialog, int which) {
               dialog.cancel();
           }
       });
    
       return builder.create();
   }
   
   
   public String AnalisisResolver(){
	   
	   int i = 0;
	   int modi=0;
	   Log.i(CLASSTAG, "Resolver");
	   StringBuilder stringBuilder = new StringBuilder();
	   StringBuilder fo = new StringBuilder();
	   String aux = new String();
    
	   for (EditText editText : editTextList) {
    	
		aux = editText.getText().toString();	//extraemos los valores
    	modi = i%(variables+1);
  		
    	if (i>=0 && i<variables+1){
    		
    		
    		if (modi == (variables)){
    			if(aux != "0"){
    				aux = "0";
    				fo.append(aux);  
    			}else{
        			fo.append(aux);                            			
    			}
    		}else{
    			
    			
    				if(idRadio==app.MAX_ID){
    					int sc = Integer.valueOf(aux);
    					int nw = sc * -1;
    					//Log.i("tag", "i "+aux);	
    					fo.append(String.valueOf(nw).concat("/1"));
    					fo.append(",");
    					
    				}else if(idRadio==app.MIN_ID){
    					fo.append(aux.concat("/1"));
                		fo.append(",");
    				}         		
            		
    		}
    		   		
    	}else{    	
         
        	 
        	 if (modi == (variables)){
        		 stringBuilder.append(aux);
                 stringBuilder.append(","); 
        		 
        	 }else{
        	 
        	 stringBuilder.append(aux.concat("/1"));
             stringBuilder.append(","); 
        	 }
         
        
    	}
    	Log.i(ACCOUNT_SERVICE, stringBuilder.toString());
        Log.i(ACCOUNT_SERVICE, String.valueOf(i%4));
       
        i++;
    }
    Log.i(ACCOUNT_SERVICE, stringBuilder.append(fo.toString()).toString());
	   
	 return stringBuilder.toString();  
   }
   
   
 public String AnalisisGraficar(){
	   
	 int i = 0;
	   int modi=0;
	   Log.i(CLASSTAG, "Resolver");
	   StringBuilder stringBuilder = new StringBuilder();
	   StringBuilder fo = new StringBuilder();
	   String aux = new String();
  
	   for (EditText editText : editTextList) {
  	
		aux = editText.getText().toString().trim();	//extraemos los valores
  	modi = i%(variables+1);
			
  	if (i>=0 && i<variables+1){
  		
  		
  		if (modi == (variables)){
  			if(aux != "0"){
				aux = "0";
				fo.append(aux);  
			}else{
    			fo.append(aux);                            			
			}                           			
  		}else{
  			
		
  				if(idRadio==app.MAX_ID){
  					int sc = Integer.valueOf(aux);
  					int nw = sc * -1;
  					fo.append(String.valueOf(nw));
  					fo.append(",");
  					
  				}else if(idRadio==app.MIN_ID){
  					fo.append(aux);
              		fo.append(",");
  				}         		
          		
  		}
  		   		
  	}else{    	
       
      	 
      	 if (modi == (variables)){
      		 stringBuilder.append(aux);
               stringBuilder.append(","); 
      		 
      	 }else{
      	 
      	 stringBuilder.append(aux);
           stringBuilder.append(","); 
      	 }
       
      
  	}
  	//Log.i(ACCOUNT_SERVICE, stringBuilder.toString());
     // Log.i(ACCOUNT_SERVICE, String.valueOf(i%4));
     
      i++;
  }
  Log.i(CLASSTAG, stringBuilder.append(fo.toString()).toString());
	   
	 return stringBuilder.toString();  
 }
   
   
 
 void MetodoRun(String me){
	 
	 double[] d = null;
	   if(idRadio==app.MAX_ID){
		    d = new SimplexMetodoTabular().maximizar(me,variables,restricciones);
	   }else if(idRadio==app.MIN_ID){
		    d = new SimplexMetodoTabular().minimizar(me,variables,restricciones); 
	   }
	   
	   String s = "";

     for (int i = 0; i < d.length - 1; i++) {
         s += d[i] + ", ";
         
     }

     s += "z=" + d[d.length - 1];
     
     Log.i(CLASSTAG,"resr = "+s);
	   
     AlertDialog alertDialog = new AlertDialog.Builder(captureData.this).create();
     alertDialog.setTitle("Resultado");
     alertDialog.setMessage(s);
     alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
  	      public void onClick(DialogInterface dialog, int which) {
  	    	  
  	       
  	 
  	    } });

     alertDialog.show();
	 
 }
 
 
 boolean validarCampos(){
	 String aux = new String();
	 int i=1;
	 for (EditText editText : editTextList) {
		 aux = editText.getText().toString();
		 Log.i(CLASSTAG, "i: "+String.valueOf(i)+"str: "+aux);
		 if(aux.equals("")){
			 Log.i("tag", "vacio null");
			 return false;
		 }
		 i++;
	 }
	 Log.i("tag", "lleno");
	 return true;
 }
 
 
 
}
